#include <network.h>
using namespace engine;

NetworkServer* g_server;

uint64 freq = 0;

uint32 getTime()
{
#ifdef WIN32
	LARGE_INTEGER v;  
    
    QueryPerformanceCounter(&v); 

	return 1000 * v.QuadPart / freq;

#else
    struct timeval v;
    gettimeofday(&v, NULL);
    return v.tv_sec * 1000 + v.tv_usec / 1000;
#endif
}

class MyServerListener : public NetworkServerListener
{
public:
	virtual void onConnected(void* net)
	{
		printf("client connected %p \n", net);
	}

	virtual void onDisconnected(void* net)
	{
		printf("client disconnected %p \n", net);
	}

	virtual void onMessage(void *net, NetworkStream& stream)
	{
		g_server->sendStream(stream, net);
	}
};

MyServerListener* g_listener;

int main()
{
#ifdef WIN32
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	LARGE_INTEGER v;
    QueryPerformanceFrequency(&v);
	freq = v.QuadPart;

#else
	struct sigaction sa;
    sa.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &sa, 0);
#endif

	g_listener = new MyServerListener();

	g_server = new NetworkServer();
	g_server->addListener(g_listener);

	if (!g_server->start(NULL, 18000, 3000))
	{
        printf("Failed to start server \n");
        exit(-1);
	}

	uint32 t = getTime();

	while (true)
	{
		if (getTime() - t < 1)
		{
			Thread::sleep(1);
		}
		else
		{
			t = getTime();

			g_server->handleMessages();
		}
	}
}
